package leetcode94;


import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Author tyy
 * @Description 94. 二叉树的中序遍历
 * 给定一个二叉树的根节点 root ，返回它的 中序 遍历。
 *
 * @Since 2021/11/14
 */
public class Solution {
    public List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        return each(root, res);
    }

    private List<Integer> each(TreeNode root, List<Integer> list) {
        if (root != null) {
            list = each(root.left, list);
            list.add(root.val);
            list = each(root.right, list);
        }
        return list;
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                cur = stack.pop();
                list.add(cur.val);
                cur = cur.right;
            }
        }
        return list;
    }


    public static void main(String[] args) {
//        String haystack = "helloworld", needle = "or";
//        int i = new Solution().strStr(haystack,needle);
//        System.out.println("i = " + i);
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
